<template>
	<view class="main_search">
		<!-- #ifdef APP-PLUS -->
		<view class="status_bar">
			<!-- 这里是状态栏，除了h5不需要，其他端都需要 -->
		</view>
		<!-- #endif -->
		<!-- 搜索头部分 start -->
		<view class="search_header">
			<view class='sea_input_part'>
				<!-- #ifndef MP -->
				<text class="back_icon iconfont iconziyuan2" @click="navBack"></text>
				<!-- #endif -->
				<view class="search_center">
					<image class="search_icon" :src="imgUrl+'search.png'"></image>
					<input class='sea_input' type='text' :value="input_val"
						:placeholder="!fromOrder?$L('请输入关键词'):$L('订单号/商品名称/店铺名称')"
						@input="inputChange" @confirm='search' maxlength="50"></input>
					<image class='clear_content' v-show="input_val" @click="clearInputVal"
						:src="imgUrl+'input_clear.png'" />
				</view>
				<text class='sea_btn' @click="btnSearch('')">{{$L('搜索')}}</text>
			</view>

			<!-- 高频搜索词 start -->
			<view class="search_association" v-if="SAList.length>0&&input_val">
				<view class="s_a_item" v-for="(item,index) in SAList" :key="index" @click="btnSearch(item.wordsContent)">
					<text>{{item.wordsContent}}</text>
					<text>{{item.searchGoodsNum}}个商品</text>
				</view>
			</view>
			<!-- 高频搜索词end -->
		</view>
		<!-- 搜索头部分 end -->

		<view v-if="SAList.length==0">
			<!-- 搜索历史 start -->
			<view v-if="history_val && history_val.length" class="search-item" :class="{searchBottom:fromOrder}">
				<view class="search-title">
					<text>{{$L('搜索历史')}}</text>
					<view class="del" @click="clearHistory">
						<image :src="imgUrl+'del_search.png'" />
					</view>
				</view>
				<view class="search-con">
					<block v-for="(item,index) in history_val" :key="index">
						<view v-if="index < 15" class="item" @click="btnSearch(item)">{{item}}</view>
					</block>
				</view>
			</view>
			<!-- 搜索历史 end -->
			
			<!-- 热门搜索 start -->
			<view class="search-item searchBottom" v-if="!fromOrder && hotSearchData && hotSearchData.length">
				<view class="search-title">
					<text>{{$L('热门搜索')}}</text>
				</view>
			
				<view class="search-con">
					<block v-for="(item,index) in hotSearchData" :key="index">
						<view class="item" @click="btnSearch(item)" v-if="item">{{item}}
						</view>
					</block>
				</view>
			</view>
			<!-- 热门搜索 end -->
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				imgUrl: getApp().globalData.imgUrl,
				input_val: '', //搜索内容
				history_val: [],
				hotSearchData: [],
				SAList:[],
				fromOrder: false, //是否从订单列表来
			}
		},
		onLoad(option) {
			if(this.$Route.query.type == 'order'){
				this.input_val = this.$Route.query.key;
				this.fromOrder = true;
			}else{
				this.getHotSearchData();
			}
			this.getHistoryList();
		},
		onShow() {
			if (this.input_val != '' && !this.fromOrder) {
				this.searchAssociation(this.input_val);
			}
		},
		methods: {
			//获取热门搜索词
			getHotSearchData() {
				var param = {}
				param.url = 'v3/system/front/setting/getSettings'
				param.data = {}
				param.data.names = 'hot_search_words'
				this.$request(param).then(res => {
					if (res.state == 200) {
						this.hotSearchData = res.data[0].split(',');
					}
				})
			},
			//获取历史记录
			getHistoryList() {
				let history_data = this.fromOrder ? 
					uni.getStorageSync('order_keyword') : uni.getStorageSync('his_keyword');
				if (history_data) {
					let his_array = history_data.split("~");
					let last_arr = [];
					for (var i = 0; i < his_array.length; i++) {
						!this.$checkSpace(his_array[i]) && last_arr.push(his_array[i]);
					}
					this.history_val = last_arr;
				}
			},
			//清除搜索历史
			clearHistory() {
				if(this.fromOrder){
					uni.removeStorageSync('order_keyword');
				}else{
					uni.removeStorageSync('his_keyword');
				}
				this.history_val = [];
			},
			inputChange(e) {
				// this.input_val = e.detail.value.trim()
				this.input_val = e.detail.value
				if(!this.fromOrder){
					if(this.input_val !=''){
						this.searchAssociation(this.input_val)
					}else{
						this.SAList.length = 0
					}
				}
			},
			//点击弹起的键盘按钮时触发
			search(e) {
				if (this.input_val != '') {
					this.btnSearch();
				}
			},
			//搜索事件
			btnSearch(val = '') {

				let {
					input_val
				} = this;

				if (val) {
					input_val = val;
					this.input_val = val;
				}

				// const ranges = [
				//   '\ud83c[\udf00-\udfff]', // U+1F300 to U+1F3FF
				//   '\ud83d[\udc00-\ude4f]', // U+1F400 to U+1F64F
				//   '\ud83d[\ude80-\udeff]', // U+1F680 to U+1F6FF
				//   ' ', // Also allow spaces
				// ].join('|');

				// const removeEmoji = str => str.replace(new RegExp(ranges, 'g'), '');
				// input_val = input_val.trim();
				// var patrn = /[`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|？：“”、；‘'。、]/g

				// if (patrn.test(input_val)) {
				// 	this.$api.msg('不能输入特殊字符')
				// 	return;
				// }
				if (input_val.length > 0) {
					this.setHistoryData();
					if(this.fromOrder){
						const pages = getCurrentPages();
						const prevPage = pages[pages.length - 2];
						prevPage.$vm.keyword = input_val;
						prevPage.$vm.refresh = true;
						this.$Router.back();
					}else{
						this.$Router.push({
							path: '/standard/product/list',
							query: {
								keyword: encodeURIComponent(input_val),
								source: 'search'
							}
						})
					}
				}
				//跳转商品列表页
			},
			//设置缓存
			setHistoryData() {
				let {
					history_val,
					input_val
				} = this;
				let tmp_data = [...history_val];
				tmp_data.unshift(input_val);
				// 最多取15条，不重复且不为空的数据
				tmp_data = tmp_data.reduce((a, b) => {
					(a.length <= 14 && b && a.indexOf(b) == -1) ? a.push(b): null;
					return a;
				}, [])
				let history_val_str = tmp_data.join('~');
				this.history_val = tmp_data;
				if(this.fromOrder){
					uni.setStorageSync("order_keyword", history_val_str)
				}else{
					uni.setStorageSync("his_keyword", history_val_str)
				}
			},
			//清空输入内容
			clearInputVal() {
				this.input_val = '';
				this.SAList = []
			},
			navBack() {
				this.$Router.back(1)
			},
			searchAssociation(value){
				this.$request({
					url:'v3/goods/front/goods/searchWords/list',
					data:{
						keyWord:value
					}
				}).then(res=>{
					this.SAList = res.data
					this.$forceUpdate()
				})
			}
		}
	}
</script>

<style lang='scss'>
	.status_bar {
		height: var(--status-bar-height);
		width: 100%;
	}
	
	.main_search{
		background: #fff;
	}

	page {
		background-color: #f7f7f7;
		width: 750rpx;
		margin: 0 auto;
	}

	.sea_input_part {
		position: relative;
		display: flex;
		align-items: center;
		height: 88rpx;

		.back_icon {
			padding-left: 20rpx;
		}

		.sea_input {
			flex: 1;
			height: 65rpx;
			font-size: 28rpx;
			color: #333;
			/* #ifdef MP-ALIPAY */
			background-color: #f5f5f5;
			/* #endif */
			
		}

		.search_center {
			display: flex;
			align-items: center;
			border: none;
			flex: 1;
			height: 65rpx;
			margin-left: 20rpx;
			padding-left: 20rpx;
			border-radius: 32.5rpx;
			background-color: #f5f5f5;

			.search_icon {
				width: 30rpx;
				height: 30rpx;
				margin-right: 13rpx;
        margin-top: 2rpx;
			}
		}

		.clear_content {
			width: 45rpx !important;
			height: 45rpx !important;
			margin-right: 15rpx !important;
		}

		.sea_btn {
			font-size: 28rpx;
			color: #2D2D2D;
			padding: 10rpx 25rpx;
			flex-shrink: 0;
		}

		&:after {
			position: absolute;
			content: '';
			left: 0;
			bottom: 0;
			width: 100%;
			height: 1rpx;
			background-color: #eee;
			transform: scaleY(0.5);
		}
	}

	.search-item {
		padding: 30rpx 28rpx 0;
		
		&.searchBottom {
			padding-bottom: 30rpx;
		}

		.search-title {
			display: flex;
			align-items: center;
			justify-content: space-between;
			height: 48rpx;
			color: #2D2D2D;
			font-size: 28rpx;
			font-weight: bold;

			image {
				width: 48rpx;
				height: 48rpx;
			}
		}

		.search-con {
			display: flex;
			align-items: center;
			flex-wrap: wrap;

			.item {
				height: 50rpx;
				padding: 0 18rpx;
				color: #2D2D2D;
				line-height: 50rpx;
				font-size: 24rpx;
				background-color: #F5F5F5;
				border-radius: 25rpx;
				margin-right: 20rpx;
				margin-top: 20rpx;
				max-width: 274rpx;
				white-space: nowrap;
				text-overflow: ellipsis;
				overflow: hidden;
				word-break: break-all;
			}
		}
	}


	.search_association {
		position: absolute;
		top: 92rpx;
		width: 750rpx;
		background: #fff;
		padding-left: 20rpx;
		z-index: 999;

		.s_a_item {
			height: 80rpx;
			display: flex;
			align-items: center;
			justify-content: space-between;
			color: #232326;
			font-size: 26rpx;
			overflow: hidden;
			white-space: nowrap;
			text-overflow: ellipsis;
			-webkit-box-flex: 1;
			padding-right: 20rpx;
			border-bottom: 1rpx solid #f0f2f5;
			text:last-child{
				color: #aaa;
			}
			
			text:first-child{
				display: block;
				max-width: 540rpx;
				overflow: hidden;
				text-overflow: ellipsis;
				white-space: nowrap;
			}
		}
	}

	.search_header {
		position: relative;
		background: #fff;
	}
</style>
